<template>
  <div class="image-resize-tool">
    <div class="tool-header">
      <h1>图片尺寸调整工具</h1>
      <p>快速调整图片尺寸和比例</p>
    </div>

    <div class="tool-container">
      <el-row :gutter="20">
        <!-- 上传区域 -->
        <el-col :span="12">
          <div class="upload-section">
            <div class="section-header">
              <h3>上传图片</h3>
            </div>
            
            <div class="upload-area">
              <el-upload
                ref="uploadRef"
                class="upload-dragger"
                drag
                :auto-upload="false"
                :show-file-list="false"
                :on-change="handleFileChange"
                accept="image/*"
              >
                <el-icon class="el-icon--upload"><upload-filled /></el-icon>
                <div class="el-upload__text">
                  将图片拖到此处，或<em>点击上传</em>
                </div>
                <template #tip>
                  <div class="el-upload__tip">
                    支持 JPG、PNG、GIF、WebP 格式
                  </div>
                </template>
              </el-upload>
            </div>
            
            <div class="file-info" v-if="originalFile">
              <h4>原始图片信息</h4>
              <div class="info-grid">
                <div class="info-item">
                  <span class="label">文件名：</span>
                  <span class="value">{{ originalFile.name }}</span>
                </div>
                <div class="info-item">
                  <span class="label">文件大小：</span>
                  <span class="value">{{ formatFileSize(originalFile.size) }}</span>
                </div>
                <div class="info-item">
                  <span class="label">原始尺寸：</span>
                  <span class="value">{{ originalImageSize }}</span>
                </div>
                <div class="info-item">
                  <span class="label">宽高比：</span>
                  <span class="value">{{ originalAspectRatio }}</span>
                </div>
              </div>
            </div>
          </div>
        </el-col>

        <!-- 调整设置和结果 -->
        <el-col :span="12">
          <div class="resize-section">
            <div class="section-header">
              <h3>尺寸调整</h3>
            </div>
            
            <div class="resize-options" v-if="originalFile">
              <div class="option-group">
                <label>调整模式：</label>
                <el-radio-group v-model="resizeMode" @change="handleModeChange">
                  <el-radio label="custom">自定义尺寸</el-radio>
                  <el-radio label="percentage">按百分比</el-radio>
                  <el-radio label="preset">预设尺寸</el-radio>
                </el-radio-group>
              </div>
              
              <!-- 自定义尺寸 -->
              <div class="option-group" v-if="resizeMode === 'custom'">
                <label>目标尺寸：</label>
                <div class="size-inputs">
                  <el-input-number
                    v-model="targetWidth"
                    :min="1"
                    :max="8000"
                    controls-position="right"
                    placeholder="宽度"
                    @change="handleCustomSizeChange"
                  />
                  <span class="separator">×</span>
                  <el-input-number
                    v-model="targetHeight"
                    :min="1"
                    :max="8000"
                    controls-position="right"
                    placeholder="高度"
                    @change="handleCustomSizeChange"
                  />
                </div>
                <div class="aspect-ratio-controls">
                  <el-checkbox v-model="maintainAspectRatio" @change="handleAspectRatioChange">
                    保持宽高比
                  </el-checkbox>
                  <el-button @click="resetToOriginal" size="small" type="info">恢复原始</el-button>
                </div>
              </div>
              
              <!-- 百分比调整 -->
              <div class="option-group" v-if="resizeMode === 'percentage'">
                <label>缩放比例：</label>
                <el-slider
                  v-model="percentage"
                  :min="10"
                  :max="500"
                  :step="5"
                  show-input
                  :show-input-controls="false"
                  @change="handlePercentageChange"
                />
                <div class="percentage-tips">
                  <span class="tip-item" :class="{ active: percentage < 50 }">缩小</span>
                  <span class="tip-item" :class="{ active: percentage >= 50 && percentage <= 150 }">正常</span>
                  <span class="tip-item" :class="{ active: percentage > 150 }">放大</span>
                </div>
              </div>
              
              <!-- 预设尺寸 -->
              <div class="option-group" v-if="resizeMode === 'preset'">
                <label>预设尺寸：</label>
                <el-select v-model="presetSize" placeholder="选择预设尺寸" @change="handlePresetChange">
                  <el-option-group label="社交媒体">
                    <el-option label="Facebook封面 (1200×630)" value="facebook-cover" />
                    <el-option label="Instagram正方形 (1080×1080)" value="instagram-square" />
                    <el-option label="Instagram故事 (1080×1920)" value="instagram-story" />
                    <el-option label="Twitter头图 (1500×500)" value="twitter-header" />
                    <el-option label="LinkedIn封面 (1584×396)" value="linkedin-cover" />
                  </el-option-group>
                  <el-option-group label="网页设计">
                    <el-option label="网页横幅 (1920×600)" value="web-banner" />
                    <el-option label="缩略图 (300×200)" value="thumbnail" />
                    <el-option label="卡片图片 (400×300)" value="card-image" />
                    <el-option label="轮播图 (1200×400)" value="carousel" />
                  </el-option-group>
                  <el-option-group label="打印尺寸">
                    <el-option label="A4 (2480×3508)" value="a4" />
                    <el-option label="名片 (1050×600)" value="business-card" />
                    <el-option label="海报 (2480×3508)" value="poster" />
                  </el-option-group>
                </el-select>
              </div>
              
              <div class="option-group">
                <label>调整算法：</label>
                <el-radio-group v-model="resizeAlgorithm">
                  <el-radio label="lanczos">Lanczos (高质量)</el-radio>
                  <el-radio label="bilinear">双线性 (快速)</el-radio>
                  <el-radio label="nearest">最近邻 (像素化)</el-radio>
                </el-radio-group>
              </div>
            </div>
            
            <div class="resize-actions" v-if="originalFile">
              <el-button 
                type="primary" 
                @click="resizeImage"
                :loading="isResizing"
                size="large"
              >
                <el-icon><Refresh /></el-icon>
                开始调整
              </el-button>
              <el-button @click="resetAll" size="large">重置</el-button>
            </div>
            
            <!-- 调整结果 -->
            <div class="result-section" v-if="resizedFile">
              <div class="section-header">
                <h3>调整结果</h3>
              </div>
              
              <div class="result-info">
                <div class="comparison">
                  <div class="comparison-item">
                    <h4>调整前</h4>
                    <div class="size-info">
                      <span class="dimensions">{{ originalImageSize }}</span>
                      <span class="size">{{ formatFileSize(originalFile.size) }}</span>
                    </div>
                  </div>
                  <div class="comparison-item">
                    <h4>调整后</h4>
                    <div class="size-info">
                      <span class="dimensions">{{ resizedImageSize }}</span>
                      <span class="size">{{ formatFileSize(resizedFile.size) }}</span>
                    </div>
                  </div>
                </div>
                
                <div class="resize-stats">
                  <el-tag type="success" size="large">
                    调整完成
                  </el-tag>
                  <el-tag type="info" size="large">
                    新尺寸: {{ resizedImageSize }}
                  </el-tag>
                </div>
              </div>
              
              <div class="result-actions">
                <el-button @click="downloadResized" type="primary" size="large">
                  <el-icon><Download /></el-icon>
                  下载调整图片
                </el-button>
                <el-button @click="previewImage" size="large">
                  <el-icon><View /></el-icon>
                  预览图片
                </el-button>
              </div>
            </div>
          </div>
        </el-col>
      </el-row>

      <!-- 使用说明 -->
      <div class="tool-info">
        <el-card>
          <template #header>
            <div class="card-header">
              <span>使用说明</span>
            </div>
          </template>
          
          <div class="info-content">
            <h4>调整模式说明：</h4>
            <ul>
              <li><strong>自定义尺寸：</strong>手动输入目标宽度和高度</li>
              <li><strong>按百分比：</strong>按比例缩放图片</li>
              <li><strong>预设尺寸：</strong>使用常用的标准尺寸</li>
            </ul>
            
            <h4>调整算法说明：</h4>
            <ul>
              <li><strong>Lanczos：</strong>最高质量，适合照片和复杂图像</li>
              <li><strong>双线性：</strong>平衡质量和速度，适合一般用途</li>
              <li><strong>最近邻：</strong>保持像素化效果，适合像素艺术</li>
            </ul>
            
            <h4>使用建议：</h4>
            <ul>
              <li>调整图片尺寸会影响文件大小</li>
              <li>放大图片可能会降低清晰度</li>
              <li>缩小图片通常能提高加载速度</li>
              <li>保持宽高比可以避免图片变形</li>
            </ul>
            
            <h4>注意事项：</h4>
            <div class="warning">
              <p>⚠️ 调整后的图片仅在前端处理，不会上传到服务器</p>
              <p>⚠️ 放大图片可能会产生模糊效果</p>
              <p>⚠️ 建议先备份原始图片</p>
            </div>
          </div>
        </el-card>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed } from 'vue'
import { ElMessage } from 'element-plus'
import { UploadFilled, Refresh, Download, View } from '@element-plus/icons-vue'

const uploadRef = ref()
const originalFile = ref(null)
const resizedFile = ref(null)
const originalImageSize = ref('')
const resizedImageSize = ref('')
const originalAspectRatio = ref('')
const resizeMode = ref('custom')
const targetWidth = ref(0)
const targetHeight = ref(0)
const percentage = ref(100)
const presetSize = ref('')
const maintainAspectRatio = ref(true)
const resizeAlgorithm = ref('lanczos')
const isResizing = ref(false)

const presetSizes = {
  'facebook-cover': { width: 1200, height: 630 },
  'instagram-square': { width: 1080, height: 1080 },
  'instagram-story': { width: 1080, height: 1920 },
  'twitter-header': { width: 1500, height: 500 },
  'linkedin-cover': { width: 1584, height: 396 },
  'web-banner': { width: 1920, height: 600 },
  'thumbnail': { width: 300, height: 200 },
  'card-image': { width: 400, height: 300 },
  'carousel': { width: 1200, height: 400 },
  'a4': { width: 2480, height: 3508 },
  'business-card': { width: 1050, height: 600 },
  'poster': { width: 2480, height: 3508 }
}

const handleFileChange = (file) => {
  const fileObj = file.raw
  if (!fileObj) return
  
  if (!fileObj.type.startsWith('image/')) {
    ElMessage.error('请选择图片文件')
    return
  }
  
  originalFile.value = fileObj
  
  // 获取图片尺寸
  const img = new Image()
  img.onload = () => {
    originalImageSize.value = `${img.width} × ${img.height}`
    originalAspectRatio.value = (img.width / img.height).toFixed(2)
    targetWidth.value = img.width
    targetHeight.value = img.height
  }
  img.src = URL.createObjectURL(fileObj)
  
  ElMessage.success('图片上传成功')
}

const handleModeChange = () => {
  if (resizeMode.value === 'percentage') {
    handlePercentageChange()
  }
}

const handleCustomSizeChange = () => {
  if (maintainAspectRatio.value && originalFile.value) {
    const img = new Image()
    img.onload = () => {
      const aspectRatio = img.width / img.height
      if (targetWidth.value !== 0) {
        targetHeight.value = Math.round(targetWidth.value / aspectRatio)
      } else if (targetHeight.value !== 0) {
        targetWidth.value = Math.round(targetHeight.value * aspectRatio)
      }
    }
    img.src = URL.createObjectURL(originalFile.value)
  }
}

const handleAspectRatioChange = () => {
  if (maintainAspectRatio.value) {
    handleCustomSizeChange()
  }
}

const handlePercentageChange = () => {
  if (originalFile.value) {
    const img = new Image()
    img.onload = () => {
      targetWidth.value = Math.round(img.width * percentage.value / 100)
      targetHeight.value = Math.round(img.height * percentage.value / 100)
    }
    img.src = URL.createObjectURL(originalFile.value)
  }
}

const handlePresetChange = () => {
  if (presetSize.value && presetSizes[presetSize.value]) {
    const size = presetSizes[presetSize.value]
    targetWidth.value = size.width
    targetHeight.value = size.height
  }
}

const resetToOriginal = () => {
  if (originalFile.value) {
    const img = new Image()
    img.onload = () => {
      targetWidth.value = img.width
      targetHeight.value = img.height
    }
    img.src = URL.createObjectURL(originalFile.value)
  }
}

const resizeImage = async () => {
  if (!originalFile.value) {
    ElMessage.warning('请先上传图片')
    return
  }
  
  if (targetWidth.value <= 0 || targetHeight.value <= 0) {
    ElMessage.warning('请输入有效的尺寸')
    return
  }
  
  isResizing.value = true
  
  try {
    // 模拟调整过程
    await new Promise(resolve => setTimeout(resolve, 1000))
    
    const canvas = document.createElement('canvas')
    const ctx = canvas.getContext('2d')
    const img = new Image()
    
    img.onload = () => {
      canvas.width = targetWidth.value
      canvas.height = targetHeight.value
      
      // 根据算法调整图片
      ctx.imageSmoothingEnabled = resizeAlgorithm.value !== 'nearest'
      ctx.imageSmoothingQuality = resizeAlgorithm.value === 'lanczos' ? 'high' : 'medium'
      
      ctx.drawImage(img, 0, 0, targetWidth.value, targetHeight.value)
      
      canvas.toBlob((blob) => {
        resizedFile.value = blob
        resizedImageSize.value = `${targetWidth.value} × ${targetHeight.value}`
        isResizing.value = false
        ElMessage.success('图片调整完成')
      }, originalFile.value.type, 0.9)
    }
    
    img.src = URL.createObjectURL(originalFile.value)
  } catch (error) {
    isResizing.value = false
    ElMessage.error('调整失败：' + error.message)
  }
}

const formatFileSize = (bytes) => {
  if (bytes === 0) return '0 Bytes'
  const k = 1024
  const sizes = ['Bytes', 'KB', 'MB', 'GB']
  const i = Math.floor(Math.log(bytes) / Math.log(k))
  return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i]
}

const downloadResized = () => {
  if (!resizedFile.value) {
    ElMessage.warning('没有可下载的文件')
    return
  }
  
  const url = URL.createObjectURL(resizedFile.value)
  const a = document.createElement('a')
  a.href = url
  a.download = `resized_${originalFile.value.name}`
  document.body.appendChild(a)
  a.click()
  document.body.removeChild(a)
  URL.revokeObjectURL(url)
  
  ElMessage.success('文件下载开始')
}

const previewImage = () => {
  if (!resizedFile.value) {
    ElMessage.warning('没有可预览的文件')
    return
  }
  
  const url = URL.createObjectURL(resizedFile.value)
  window.open(url, '_blank')
}

const resetAll = () => {
  originalFile.value = null
  resizedFile.value = null
  originalImageSize.value = ''
  resizedImageSize.value = ''
  originalAspectRatio.value = ''
  resizeMode.value = 'custom'
  targetWidth.value = 0
  targetHeight.value = 0
  percentage.value = 100
  presetSize.value = ''
  maintainAspectRatio.value = true
  resizeAlgorithm.value = 'lanczos'
  uploadRef.value?.clearFiles()
  ElMessage.info('已重置所有设置')
}
</script>

<style scoped>
.image-resize-tool {
  max-width: 1200px;
  margin: 0 auto;
  padding: 20px;
}

.tool-header {
  text-align: center;
  margin-bottom: 40px;
}

.tool-header h1 {
  font-size: 2.5rem;
  color: #333;
  margin-bottom: 10px;
}

.tool-header p {
  color: #666;
  font-size: 1.1rem;
}

.tool-container {
  margin-bottom: 40px;
}

.upload-section,
.resize-section {
  background: white;
  border-radius: 12px;
  padding: 24px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
  border: 1px solid #f0f0f0;
  height: 100%;
}

.section-header {
  margin-bottom: 20px;
}

.section-header h3 {
  color: #333;
  margin: 0;
  font-size: 1.3rem;
}

.upload-area {
  margin-bottom: 20px;
}

.upload-dragger {
  width: 100%;
}

.file-info {
  background: #f8f9fa;
  padding: 20px;
  border-radius: 8px;
  border: 1px solid #e9ecef;
}

.file-info h4 {
  margin: 0 0 15px 0;
  color: #333;
  font-size: 1.1rem;
}

.info-grid {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 10px;
}

.info-item {
  display: flex;
  justify-content: space-between;
  padding: 8px 0;
  border-bottom: 1px solid #e9ecef;
}

.info-item:last-child {
  border-bottom: none;
}

.label {
  font-weight: 500;
  color: #666;
}

.value {
  color: #333;
  font-family: 'Courier New', monospace;
}

.resize-options {
  margin-bottom: 30px;
}

.option-group {
  margin-bottom: 25px;
}

.option-group label {
  display: block;
  margin-bottom: 10px;
  font-weight: 500;
  color: #333;
}

.size-inputs {
  display: flex;
  align-items: center;
  gap: 10px;
  margin-bottom: 10px;
}

.separator {
  color: #666;
  font-weight: bold;
}

.aspect-ratio-controls {
  display: flex;
  align-items: center;
  gap: 15px;
}

.percentage-tips {
  display: flex;
  justify-content: space-between;
  margin-top: 10px;
}

.tip-item {
  padding: 4px 8px;
  border-radius: 4px;
  font-size: 0.8rem;
  color: #666;
  background: #f0f0f0;
}

.tip-item.active {
  background: #667eea;
  color: white;
}

.resize-actions {
  display: flex;
  gap: 12px;
  margin-top: 30px;
}

.result-section {
  margin-top: 30px;
  padding: 20px;
  background: #f8f9fa;
  border-radius: 8px;
  border: 1px solid #e9ecef;
}

.result-info {
  margin-bottom: 20px;
}

.comparison {
  display: flex;
  justify-content: space-around;
  margin-bottom: 20px;
}

.comparison-item {
  text-align: center;
}

.comparison-item h4 {
  margin: 0 0 15px 0;
  color: #333;
}

.size-info {
  display: flex;
  flex-direction: column;
  gap: 5px;
}

.dimensions {
  font-size: 1.2rem;
  font-weight: bold;
  color: #667eea;
}

.size {
  color: #666;
  font-size: 0.9rem;
}

.resize-stats {
  display: flex;
  justify-content: center;
  gap: 15px;
}

.result-actions {
  display: flex;
  gap: 12px;
  justify-content: center;
}

.tool-info {
  margin-top: 40px;
}

.card-header {
  font-weight: bold;
  color: #333;
}

.info-content h4 {
  color: #333;
  margin: 20px 0 10px 0;
  font-size: 1.1rem;
}

.info-content p {
  color: #666;
  line-height: 1.6;
  margin-bottom: 15px;
}

.info-content ul {
  color: #666;
  padding-left: 20px;
  margin-bottom: 15px;
}

.info-content li {
  margin-bottom: 5px;
}

.warning {
  background: #fff3cd;
  padding: 15px;
  border-radius: 8px;
  border-left: 4px solid #ffc107;
  margin: 15px 0;
}

.warning p {
  margin: 5px 0;
  color: #856404;
}

@media (max-width: 768px) {
  .tool-header h1 {
    font-size: 2rem;
  }
  
  .info-grid {
    grid-template-columns: 1fr;
  }
  
  .size-inputs {
    flex-direction: column;
    align-items: stretch;
  }
  
  .aspect-ratio-controls {
    flex-direction: column;
    align-items: flex-start;
  }
  
  .comparison {
    flex-direction: column;
    gap: 15px;
  }
  
  .resize-stats {
    flex-direction: column;
    align-items: center;
  }
  
  .result-actions {
    flex-direction: column;
  }
}
</style>
